package corbaServer.dao;

import java.sql.SQLException;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.Statement;
//import java.util.Date;
import java.util.LinkedList;
import java.util.List;
import corbaServer.RaceDO;


public class CorbaRaceServerDAO implements ICorbaRaceServerDAO {
	private java.sql.Connection con;
	private String dbname;
	private String serverName;
	public void connect() {
		try{
            Class.forName("org.sqlite.JDBC");
            con = DriverManager.getConnection("jdbc:sqlite:db/corba-db/" + dbname);
//            con = DriverManager.getConnection("jdbc:sqlite:db/corba-db/gipuzkoaraces.db");
            System.out.println("Database connection established.");
		}    
		catch (SQLException ex){
            System.out.println("Error connecting to the database." + ex.getMessage()); 
		}catch (ClassNotFoundException e){
			System.out.println("Error connecting to the database." + e.getMessage()); 
		}

	}

	public List<RaceDO> getRaces() throws SQLException {
		LinkedList<RaceDO> races= new LinkedList<RaceDO>();
		System.out.println("CorbaRaceServerDAO executing...");
		
		ResultSet result;
        try {
                Statement stmt = con.createStatement();
                String query= "SELECT * FROM races";
                result = stmt.executeQuery(query);
        } catch (SQLException e) {
                System.out.println("Query error");
                throw e;
        }
        while(result.next()){
        	String name= result.getString("name");
        	float dist= result.getFloat("distance");
        	String date= result.getString("date");
        	int places= result.getInt("places");
        	RaceDO rdo= new RaceDO(name, dist, date, places);
        	races.add(rdo);
        }
		
		return races;
	}

	public void disconnect() {
		try {
			con.close();
		} catch (SQLException e) {
			System.out.println("Error disconnecting from the database." + e.getMessage());
		}
	}

	
	public void setDbName(String serverName){
		this.dbname= serverName.toLowerCase() + ".db";
		System.out.println("Database name using: " + this.dbname);
	}
	
	public void setServerName(String pName){
		this.serverName= pName;
		this.setDbName(pName);
		System.out.println("Server name set to: " + this.serverName);
	}
	
	
}
